import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login.vue')
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('@/views/register.vue') 
  },
  {
    path: '/index',
    name: 'index',
    component: () => import('@/views/index.vue'),
    redirect: '/home',
    children: [
      {
        path: '/home',
        name: 'home',
        component: () => import('@/views/home.vue'),
        meta: { title: '首页' }
      },
      {
        path: '/center',
        name: 'center',
        component: () => import('@/views/center.vue'),
        meta: { title: '个人中心' }
      },
      {
        path: '/update-password',
        name: 'update-password',
        component: () => import('@/views/update-password.vue'),
        meta: { title: '修改密码' }
      },
      {
        path: '/announcement',
        name: 'announcement',
        component: () => import('@/views/announcement.vue'),
        meta: { title: '公告通知' }
      },
      {
        path: '/repair-manager',
        name: 'repair-manager',
        component: () => import('@/views/repair-manager.vue'),
        meta: { 
          title: '报修管理',
          role: ['admin', 'suguan']
        }
      },
      {
        path: '/student-repair',
        name: 'student-repair',
        component: () => import('@/views/sushebaoxiu.vue'),
        meta: { 
          title: '宿舍报修申请',
          role: ['xuesheng']
        }
      },
      {
        path: '/dorm-inspection',
        name: 'dorm-inspection',
        component: () => import('@/views/dorm_inspection.vue'),
        meta: { title: '宿舍内务检查' }
      },
      {
        path: '/student-inspection',
        name: 'student-inspection',
        component: () => import('@/views/student_inspection.vue'),
        meta: { title: '宿舍内务检查记录' }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'not-found',
    component: () => import('@/views/404.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// Navigation guard for authentication
router.beforeEach((to, from, next) => {
  // Exclude login and register pages from requiring auth
  const publicPages = ['/login', '/register']
  const authRequired = !publicPages.includes(to.path)
  const token = localStorage.getItem('Token')
  
  if (authRequired && !token) {
    next('/login')
  } else {
    next()
  }
})

export default router 